import _ from 'lodash'
import React, { Component } from 'react'
import { UdForm, IUdFormItem, validators, http } from '@/lib'
import { Button, InputNumber, Input, Radio, message, Select } from 'antd'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import IconSelector from '@components/IconSelector'
import { ESystemMenuType } from '@/utils/types'
import apis from '@/apis/MenusManage'
import { formUtils } from '@/lib/utils/formUtils'

const { Option } = Select


class MenuForm extends Component<IMenuFormProps, IMenuFormState> {

  private form: WrappedFormUtils = {} as any
  private requestMethods = [
    { value: 'GET', title: 'GET' },
    { value: 'POST', title: 'POST' },
    { value: 'DELETE', title: 'DELETE' },
    { value: 'PUT', title: 'PUT' },
    { value: 'PATCH', title: 'PATCH' },
  ]

  constructor(props: IMenuFormProps) {
    super(props)
    this.state = {
      values: {},
      menuType: '',
      submitLoading: false
    }
  }

  componentWillReceiveProps(nextProps: IMenuFormProps) {
    if (!_.isEqual(this.props, nextProps)) {
      this.form.resetFields()
      if (nextProps.type === 'add') {
        if (nextProps.node == null) {
          this.setState({ menuType: ESystemMenuType['MENU_GROUP'] })
        } else if (nextProps.node.type == ESystemMenuType['MENU_ITEM']) {
          // 如果是新增菜单项的子级（即资源），则处理当前新增menuType为资源
          this.setState({ menuType: ESystemMenuType['RESOURCE'] })
        } else if (nextProps.node.type == ESystemMenuType['MENU_GROUP']) {
          // 如果是新增组项的子级（即菜单），则处理当前新增menuType为菜单
          this.setState({ menuType: ESystemMenuType['MENU_ITEM'] })
        }
      } else if (nextProps.type === 'edit') {
        this.setState({ menuType: nextProps.node?.type })
        this.getDetails(nextProps)
      } else {
        this.form.resetFields()
      }
    }
  }

  render() {
    let { type, node } = this.props
    let { menuType } = this.state
    console.log('form', type, node)

    let types: any[] = []

    types.push(<Radio value={ESystemMenuType['MENU_GROUP']} disabled={this.isMenuGroupNode(node) || !node ? false : true}>菜单组</Radio>)
    types.push(<Radio value={ESystemMenuType['MENU_ITEM']} disabled={!this.isMenuItemNode(node) || !node ? false : true}>菜单项</Radio>)
    types.push(<Radio value={ESystemMenuType['RESOURCE']} disabled={this.isMenuGroupNode(node) || !node ? true : false}>资源</Radio>)

    let items: IUdFormItem[] = [
      { label: '名称', id: 'text', rules: [validators.required, validators.max(200)] },
      {
        label: '类型', id: 'menuType', rules: [validators.required],
        render: <Radio.Group disabled={type == 'edit'} onChange={(e) => this.setState({ menuType: e.target.value })}>
          {types}
        </Radio.Group>
      },
      { label: '图标', id: 'icon', render: <IconSelector /> },
      {
        label: '排序', id: 'orderIndex',
        render: <InputNumber max={10000} min={0} precision={0} />
      },
      { label: '自定义Id', id: 'customId', rules: [validators.required, validators.max(64)], render: (
        <Input disabled={type === 'edit'} />
      ) },
      { label: 'url', id: 'url', rules: [validators.required, validators.max(200)] },
      { label: '请求方式', id: 'requestMethod', render: (
        <Select>{this.requestMethods.map(({ value, title }) => <Option key={value} value={value}>{title}</Option>)}</Select>
      ) },
    ]
    if (menuType == ESystemMenuType['RESOURCE']) {
      items = items.map(item=>{
        if (item.id === 'requestMethod') {
          item.rules = [validators.required]
        }
        return item
      })
      _.remove(items, n => n.id == 'icon')
    }
    if (menuType == ESystemMenuType['MENU_GROUP']) {
      _.remove(items, n => n.id == 'requestMethod')
      _.remove(items, n => n.id == 'url')
    }
    if (menuType !== ESystemMenuType['MENU_GROUP'] && this.props.parentName) {
      items.unshift({ label: '父级菜单', id: 'application', render: <div>{this.props.parentName}</div> },)
    }


    return (
      <div className="menu-form">
        <div className="box-title">{type == 'add' ? '添加菜单' : '编辑菜单'}</div>

        <UdForm
          getForm={e => this.form = e}
          items={items}
          values={this.state.values}
          footer={
            <Button type="primary" loading={this.state.submitLoading} onClick={this.submitData}>保存</Button>
          }
        />
      </div>
    )
  }

  private getDetails = (props: IMenuFormProps) => {
    const { id } = props.node
    http.get(apis.MenuDetail, {params: {id}}).then(res=>{
      let values = res.data
      values.menuType = values.type
      // const { title: text, key: customId } = values
      this.setState({ values })
    })
  }

  protected submitData = () => {
    this.form.validateFieldsAndScroll((errors, values) => {
      if (!errors) {
        let result = formUtils.handleValues(values, true)
        this.submitRequest(result)
      }
    })
  }

  public submitRequest = (values) => {

    this.setState({submitLoading: true})
    const { type, parentKey, node, appCode } = this.props
    let ajaxUrl: string = ''
    let methodType: string = ''

    values.accountType = appCode
    values.application = parentKey
    if (type === 'add') {
      ajaxUrl = apis.AddMenu
      methodType = 'post'
    } else if (type === 'edit') {
      ajaxUrl = apis.UpdateMenu
      values.id = node.id
      methodType = 'put'
    }
    // 处理数据level  组:0  菜单:1  资源:2
    switch (values.menuType) {
      case ESystemMenuType['MENU_GROUP']:
        values.level = 0
        break;
      case ESystemMenuType['MENU_ITEM']:
        values.level = 1
        break;
      case ESystemMenuType['RESOURCE']:
        values.level = 2
        break;
    }
    values.orderIndex = values.orderIndex ? values.orderIndex : 0

    http[methodType](ajaxUrl, values).then(res => {
      message.success('操作成功')
      // this.form.resetFields()
      this.props.submitSuccess()
    }).finally(()=>this.setState({submitLoading: false}))
  }

  public isMenuGroupNode = (node) => {
   return node && node.type === ESystemMenuType['MENU_GROUP']
  }

  public isMenuItemNode = (node) => {
   return node && node.type === ESystemMenuType['MENU_ITEM']
  }

  public isResourceNode = (node) => {
   return node && node.type === ESystemMenuType['RESOURCE']
  }
}

interface IMenuFormProps {
  appCode: string | number
  parentKey: string
  parentName: string
  type: 'add' | 'edit' | 'delete'
  node: any,
  submitSuccess?: any
}

interface IMenuFormState {
  values: any
  menuType: string
  submitLoading?: boolean
}

export default MenuForm
